﻿using Hangfire;
using LJ.Abstractions;
using LJ.Abstractions.Pack;
using LJ.TaskScheduler.Abstractions.Pack;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace LJ.TaskScheduler.Hangfire.Pack;

public class TaskSchedulerHangfirePackBase : TaskSchedulerPackBase
{
    public override void Add(IPackContext packContext)
    {
        packContext.ServiceCollection.AddSingleton<BackgroundJobServer>(a =>
        {
            var options = new BackgroundJobServerOptions
            {
                ServerName = "task",//服务名
                //检测时间
                SchedulePollingInterval = TimeSpan.FromSeconds(5),
                //心跳时间
                HeartbeatInterval = TimeSpan.FromSeconds(5),
                //总工作数
                WorkerCount = Math.Max(Environment.ProcessorCount, 20)
            };
            return new BackgroundJobServer(options);
        });

        var taskSchedulerHangfirePackBuilder = new TaskSchedulerHangfirePackBuilder();
        _= new TaskSchedulerManager(packContext.ServiceCollection, packContext.ReflectionManager, taskSchedulerHangfirePackBuilder);
        packContext.ServiceCollection.AddSingleton<ITaskSchedulerHangfirePackBuilder>(taskSchedulerHangfirePackBuilder);
    }

    public override void Use(IPackProvider packProvider)
    {
        GlobalConfiguration.Configuration.UseActivator(new HangfireTaskSchedulerJobActivator(packProvider.ServiceProvider));
    }

    public override Task StartAsync(IAppProvider appProvider)
    {
        _ = appProvider.ServiceProvider.GetRequiredService<BackgroundJobServer>();
        return Task.CompletedTask;
    }

    public override Task StopAsync(IAppProvider appProvider)
    {
        var backgroundJobServer = appProvider.ServiceProvider.GetRequiredService<BackgroundJobServer>();
        backgroundJobServer.Dispose();
        return Task.CompletedTask;
    }
}
